package com.tenement.action;

import com.google.gson.Gson;
import com.tenement.domain.TenementLog;
import com.tenement.domain.TenementUser;
import com.tenement.service.LogService;
import com.tenement.service.UserService;
import com.tenement.utils.Message;
import com.tenement.utils.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName : UserAction  //类名
 * @Description : 用户Controller  //描述
 * @Author : 易嵘  //作者
 * @Date: 2020-06-06 12:30  //时间
 */
@Controller
@RequestMapping("userAction")
public class UserAction {

    /**
     * 用户服务接口
     */
    @Resource
    UserService userService;

    @Resource
    LogService logService;

    /**
     * 查询所有（条件，分页）
     *
     * @param user  用户模型
     * @param page  当前页数
     * @param limit 显示行数
     * @return
     */
    @RequestMapping("findAll")
    @ResponseBody
    public Map<String, Object> findAll(TenementUser user,
                                       @RequestParam(value = "startDate", required = false) String startDate,
                                       @RequestParam(value = "endDate", required = false) String endDate,
                                       @RequestParam("page") Integer page,
                                       @RequestParam("limit") Integer limit) {

        List<TenementUser> list = userService.selecrAll(user, page, limit, startDate, endDate);

        Long overCount = userService.overCount(user, startDate, endDate);

        return Tools.maps(overCount, list);
    }

    /**
     * 查询所有(不包含管理员)
     *
     * @return
     */
    @RequestMapping("selectAll")
    @ResponseBody
    public List<TenementUser> selectAll() {

        return userService.findAll();
    }

    /**
     * 查询所有
     * @return
     */
    @RequestMapping("findAlls")
    @ResponseBody
    public List<TenementUser> findAlls(){
        return userService.findAlls();
    }

    @RequestMapping("findById")
    @ResponseBody
    public TenementUser findById(String id) {
        return userService.findById(id);
    }

    /**
     * 新增Or修改
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("addOrUpdate")
    public Message addOrUpdate(TenementUser user, HttpSession session,HttpServletRequest request) {
        String ip=request.getRemoteAddr();
        TenementUser user1 = (TenementUser) session.getAttribute("user");
        int row = 0;
        if (StringUtils.isEmpty(user.getUserId())) {
            row = userService.add(user, user1,ip);
        } else {
            row = userService.update(user, user1,ip);
        }
        return Tools.rows(row);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteById")
    public Message deleteById(String id,HttpServletRequest request) {
        TenementUser user= (TenementUser) request.getSession().getAttribute("user");
        String ip=request.getRemoteAddr();
        int row = userService.deleteById(id,user,ip);
        return Tools.rows(row);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteAll")
    public Message deleteAll(@RequestParam(value = "ids[]", required = false) String ids[],HttpServletRequest request) {

        TenementUser user= (TenementUser) request.getSession().getAttribute("user");
        String ip=request.getRemoteAddr();
        int row = userService.deleteAll(ids,user,ip);
        return Tools.rows(row);
    }

    /**
     * 判断登录
     *
     * @param tenementUser
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("findManager")
    public Message findManager(TenementUser tenementUser, String usweiid, HttpSession session, HttpServletRequest request) {
        Message message = new Message();
        TenementUser user = userService.isLogin(tenementUser);
        if (ObjectUtils.isEmpty(user)) {
            message.setMsg("密码错误");
            message.setNum(1);
        } else {
            String ip = request.getRemoteAddr(); //取登陆人的ip
            TenementLog log=new TenementLog();
            log.setLogId(UUID.randomUUID().toString().replaceAll("-",""));
            log.setLogTitle("用户登录");
            log.setLogType(0);
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dates=sdf.format(date);
            StringBuffer logBody=new StringBuffer();
            Tools.logUserMod(user,logBody);
            log.setLogBody(logBody+";登录设备：PC");
            log.setLogIp(ip);
            log.setCreatedBy(user.getUserName());
            if(!StringUtils.isEmpty(usweiid)){
                log.setLogBody(logBody+";登录设备：微信小程序");
                user.setWxUser(usweiid);
                userService.update(user,user, ip);
            }
            logService.add(log);
            session.setAttribute("user", user);
            message.setMsg("登录成功");
            message.setNum(0);
        }
        return message;
    }

    /**
     * 查询是否已经登录
     *
     * @param session
     * @return
     */
    @RequestMapping("/findModByManager")
    @ResponseBody
    public TenementUser findModByManager(HttpSession session) {

        TenementUser man = (TenementUser) session.getAttribute("user");
        if (man == null) {
            man = new TenementUser();
            man.setUserId("0");
            man.setUserName("请重新登录");
        }
        return man;
    }

    @RequestMapping("/updatePwd")
    @ResponseBody
    public Message updatePwd( String newUserPassword,HttpSession session,HttpServletRequest request) {
        TenementUser user= (TenementUser) session.getAttribute("user");
        String ip = request.getRemoteAddr();
        user.setUserPassword(newUserPassword);
        int row= userService.update(user,user, ip);
        return Tools.rows(row);
    }

    /**
     * 日期格式化
     *
     * @param binder
     */
    /*@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); // true:允许输入空值，false:不能为空值

    }*/

}
